<script setup lang="ts">
import {
  reactive,
  getCurrentInstance,
  ComponentInternalInstance,
  defineEmits,
  onMounted,
} from "vue";
import { themeStore, ITheme } from "@/store/modules/theme";
import moment from "moment";
import language from "@/lang/zh";
const themeColors: ITheme = themeStore().theme;
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const emits = defineEmits(["listenLink"]);

const state: any = reactive({
  showPopup: false,
  curMode: "dark",
  list: [],
  userInfo: null,
  isEdit: false,
});
const goConsultation = () => {
  state.showPopup = false;
};
// 激活
const active = () => {
  getTop3QaList();
  state.showPopup = true;
};
defineExpose({
  active,
});
//
const getTop3QaList = () => {
  proxy?.$api
    .get(process.env.VUE_APP_BASE_API_URL + "/wechatApi/getUserQAList")
    .then((res: any) => {
      if (res.code === 200 && res.data?.length > 0) {
        let data = res.data;
        for (let i = 0; i < data.length; i++) {
          let newList: any = [];
          for (let j = 0; j < data[i].list.length; j++) {
            newList = newList.concat([
              {
                type: 0,
                text: data[i].list[j].questionContent,
                fileList: data[i].list[j].resourceFile
                  ? data[i].list[j].resourceFile.split(",")
                  : [],
              },
              {
                ...data[i].list[j],
              },
            ]);
          }
          data[i].qaList = newList;
        }
        state.list = data;
      }
    });
};
const props = defineProps({
  selectOldWin: {
    type: String,
    default: "",
  },
  state: {
    type: Boolean,
    default: "",
  },
});
onMounted(() => {
  state.userInfo = JSON.parse(localStorage.getItem("userInfo"));
});
const clearQaList = (id: string) => {
  proxy?.$api
    .post(process.env.VUE_APP_BASE_API_URL + "/wechatApi/delUserSession", {
      sessionId: id,
    })
    .then((res: any) => {
      if (res.code === 200) {
        const index = state.list.findIndex((i: any) => i.sessionId === id);
        state.list.splice(index, 1);
        proxy.$showToast("清除成功");
      } else {
        proxy.$showToast(res.msg);
      }
    });
};
const getFileDetails = (item: any) => {
  return new Promise((resolve) => {
    if (item.resourceFile && item.fileId) {
      let urls = item.resourceFile.split(",");
      let ids = item.fileId.split(",");
      let docList: any = [];
      for (let i = 0; i < urls.length; i++) {
        const url = urls[i];
        fetch(url, {
          method: "HEAD", // 只获取文件头部信息
        })
          .then((response) => {
            // 获取文件大小（Content-Length header）
            const fileSize = response.headers.get("Content-Length");
            // 从 URL 中提取文件名
            const fileName = url.substring(url.lastIndexOf("/") + 1);
            docList.push({
              file_name: fileName,
              file_size: sizeFileZh(Number(fileSize)),
              url: url,
              file_id: ids[i],
            });
            if (docList.length === urls.length) {
              console.log(docList, "docList");
              resolve(docList)
            }
          })
          .catch((error) => {
            console.error("无法获取文件信息", error);
          });
      }
    }
  });
};

const sizeFileZh = (fileSize: number) => {
  var size = "";
  if (fileSize < 0.1 * 1024) {
    //如果小于0.1KB转化成B
    size = fileSize.toFixed(2) + "B";
  } else if (fileSize < 0.1 * 1024 * 1024) {
    //如果小于0.1MB转化成KB
    size = (fileSize / 1024).toFixed(2) + "KB";
  } else if (fileSize < 0.1 * 1024 * 1024 * 1024) {
    //如果小于0.1GB转化成MB
    size = (fileSize / (1024 * 1024)).toFixed(2) + "MB";
  } else {
    //其他转化成GB
    size = (fileSize / (1024 * 1024 * 1024)).toFixed(2) + "GB";
  }

  var sizestr = size + "";
  var len = sizestr.indexOf(".");
  var dec = sizestr.substr(len + 1, 2);
  if (dec == "00") {
    //当小数点后为00时 去掉小数部分
    return sizestr.substring(0, len) + sizestr.substr(len + 3, 2);
  }
  return sizestr;
};
const setNewQa = async (e: string, list: any) => {
  let item = state.list.find((i: any) => i.sessionId === e);
  let newList: any = [];
  for (let j = 0; j < item.list.length; j++) {
    if (item.list[j].questionType === 6) {
      newList = newList.concat([
        {
          type: 0,
          text: item.list[j].questionContent,
          fileList: item.list[j].resourceFile
            ? item.list[j].resourceFile.split(",")
            : [],
        },
        {
          ...item.list[j],
        },
      ]);
    } else if (item.list[j].questionType === 7) {
      let fileListDoc = await  getFileDetails(item.list[j]);
      newList = newList.concat([
        {
          type: 0,
          text: item.list[j].questionContent,
          fileListDoc,
        },
        {
          ...item.list[j],
        },
      ]);
    } else {
      newList = newList.concat([
        {
          type: 0,
          text: item.list[j].questionContent,
        },
        {
          ...item.list[j],
        },
      ]);
    }
  }
  console.log(newList, "12312312313");
  item.qaList = newList;
  emits("listenLink", { id: e, list: newList });
  state.showPopup = false;
};
</script>

<template>
  <!-- 右侧弹出 -->
  <van-popup
    v-model:show="state.showPopup"
    position="right"
    close-icon-position="top-right"
    class="characterPopup"
    :style="{ width: '93%', height: '100%' }"
    z-index="999999"
  >
    <div class="con">
      <div class="top">
        <div class="top-detail">
          <span>{{
            props.state
              ? language.messageEN.history
              : language.messageZH.history
          }}</span>
        </div>
        <div class="edit">
          <span v-if="!state.isEdit" @click="state.isEdit = true">{{
            props.state ? language.messageEN.edit : language.messageZH.edit
          }}</span>
          <span v-if="state.isEdit" @click="state.isEdit = false">{{
            props.state ? language.messageEN.done : language.messageZH.done
          }}</span>
          <div class="close" @click="state.showPopup = false">
            <van-icon name="cross" />
          </div>
        </div>
      </div>
      <div class="hislist">
        <div class="title">
          {{
            props.state ? language.messageEN.recent : language.messageZH.recent
          }}
        </div>
        <div class="list" v-if="state.list.length > 0">
          <div
            class="item-box"
            v-for="(item, index) in state.list"
            :key="index"
          >
            <div
              class="list-item"
              :style="{ width: state.isEdit ? 'calc(100% - 32px)' : '100%' }"
              @click="setNewQa(item.sessionId, item.qaList)"
            >
              <span class="fs-26">
                <div class="content-text">
                  <b></b>
                  <div>{{ item.sessionName }}</div>
                </div>
                <div class="date">
                  {{ moment(item.questionTime).format("MM-DD") }}
                </div>
              </span>
            </div>
            <div
              class="del"
              v-if="state.isEdit"
              @click="clearQaList(item.sessionId)"
            >
              <span class="iconfont icon-shanchu1"></span>
            </div>
          </div>
        </div>
      </div>
      <!-- <div class="avatar">
        <img :src="state.userInfo?.user?.avatar" />
        <span class="fs-32">{{state.userInfo?.user?.userName}}</span>
      </div> -->
      <!-- <div class="history">
        <span class="fs-32">历史问题</span>
        <div class="back" @click="goConsultation">
          <span class="iconfont icon-jiantou"></span>
        </div>
      </div> -->

      <!-- <div class="clear" v-if="state.list.length > 0" @click="clearQaList">
        <span class="iconfont icon-shanchu1"></span>
        <span>全部清除</span>
      </div> -->
      <!-- 其他设置 -->
      <!-- <div class="other-setting">
        <div class="item">
          <div class="left">
            <span class="iconfont icon-taiyang"></span>
            <span>模式切换</span>
          </div>
          <div class="right right-check-mode">
            <div
              class="dark"
              :class="{
                active: state.curMode === 'dark',
              }"
              @click="state.curMode = 'dark'"
            >
              <span class="iconfont icon-taiyang"></span>
            </div>
            <div
              class="light"
              @click="state.curMode = 'light'"
              :class="{
                active: state.curMode === 'light',
              }"
            >
              <span class="iconfont icon-yueliang"></span>
            </div>
          </div>
        </div>
        <div class="item">
          <div class="left">
            <span class="iconfont icon-a-kefukefuzhongxin"></span>
            <span>帮助中心</span>
          </div>
          <div class="right">
            <span class="iconfont icon-jiantou"></span>
          </div>
        </div>
        <div class="item">
          <div class="left">
            <span class="iconfont icon-anquan"></span>
            <span>安全中心</span>
          </div>
          <div class="right">
            <span class="iconfont icon-jiantou"></span>
          </div>
        </div>
      </div> -->
    </div>
    <!-- <div class="logout">
      <span class="iconfont icon-zhuxiao"></span>
      <span>注销</span>
    </div> -->
  </van-popup>
</template>

<style lang="scss" scoped>
.van-popup__close-icon--top-right {
  top: 46px;
}
.characterPopup {
  width: 73%;
  height: 100%;
  border-radius: 24px 0 0 24px;
  background: v-bind("themeColors.fillColorLightest");
  box-shadow: 0px 2px 4px rgba(0, 0, 0, 0.06);
  padding: 40px 40px 80px 40px;
  .bg {
    position: absolute;
    left: 0px;
    top: 0px;
    width: 100%;
    height: 818px;
    background-size: contain;
    background-image: url("@/assets/images/bg.png");
    background-repeat: no-repeat;
  }
  .con {
    display: flex;
    position: relative;
    flex-direction: column;
    .top {
      display: flex;
      align-items: center;
      justify-content: space-between;
      .top-detail {
        display: flex;
        align-items: center;
        font-weight: bold;
      }
      .edit {
        font-weight: 300;
        color: #000;
        font-size: 32px;
        display: flex;
        .close {
          margin-left: 40px;
        }
      }
      .back {
        width: 84px;
        height: 56px;
        border-radius: 720px;
        transform: rotate(180deg);
        background: rgba(255, 255, 255, 0.2);
        display: flex;
        align-items: center;
        justify-content: center;
        span {
          font-size: 28px;
          color: v-bind("themeColors.textColorLightest");
        }
      }
      .logo {
        margin-left: 44px;
        height: 42px;
      }
    }
    .avatar {
      display: flex;
      justify-content: center;
      flex-direction: column;
      align-items: center;
      color: v-bind("themeColors.textColorLightest");
      // margin: 80px 0;
      img {
        width: 136px;
        height: 136px;
        border-radius: 50%;
        background: #f5f5f5;
        margin-bottom: 6px;
      }
    }
    .history {
      display: flex;
      justify-content: space-between;
      align-items: center;
      span {
        font-weight: 500;
        color: v-bind("themeColors.textColor");
      }
      .back {
        display: flex;
        align-items: center;
        justify-content: center;
        background: v-bind("themeColors.fillColorLightest");
        width: 84px;
        height: 56px;
        border-radius: 720px;
        span {
          font-size: 28px;
          color: v-bind("themeColors.textColor");
        }
      }
    }
    .hislist {
      & > .title {
        margin-top: 40px;
        font-size: 30px;
      }
    }
    .list {
      display: flex;
      width: 100%;
      flex-direction: column;
      color: #333;
      background: v-bind("themeColors.fillColorLightest");
      margin-top: 30px;
      box-shadow: 0px 2px 8px rgba(0, 0, 0, 0.05);
      max-height: 70vh;
      overflow-y: scroll;
      &::-webkit-scrollbar {
        display: none;
      }
      .item-box {
        display: flex;
        align-items: center;
        margin-bottom: 20px;
        justify-content: space-between;
        .del {
          display: flex;
          align-items: center;
          justify-content: center;
          width: 64px;
          color: #d81e06;
        }
      }
      .list-item {
        display: flex;
        justify-content: space-between;
        width: 100%;
        border-radius: 8px;
        background: rgba(80, 119, 186, 0.1);
        padding: 20px 24px;
        display: flex;
        align-items: center;
        overflow: hidden;
        .content-text {
          max-width: calc(100% - 80px);
          display: flex;
          align-items: center;
        }
        .date {
          width: 150px;
          text-align: right;
          display: flex;
          justify-content: flex-end;
          color: #a8a6a6;
        }
        span {
          display: flex;
          align-items: center;
          justify-content: space-between;
          width: 100%;
          div {
            width: 100%;
            overflow: hidden; /* 确保超出容器的文本被裁剪 */
            white-space: nowrap; /* 防止文本换行 */
            text-overflow: ellipsis; /* 用省略号显示被裁剪的文本 */
          }
          b {
            display: flex;
            width: 16px;
            height: 16px;
            background: v-bind("themeColors.fillColorDarken");
            margin-right: 16px;
            border-radius: 50%;
            flex-shrink: 0;
          }
        }
      }
    }
    .clear {
      display: flex;
      justify-content: flex-end;
      color: v-bind("themeColors.fillColorDarken");
      margin-top: 16px;
      span {
        font-size: 24px;
        margin-left: 4px;
        &:first-child {
          margin-left: 0;
        }
      }
    }
    .other-setting {
      display: flex;
      margin-top: 72px;
      flex-direction: column;
      .item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-top: 44px;
        .left {
          span {
            color: v-bind("themeColors.textColor");
            font-size: 32px;
            &:first-child {
              margin-right: 16px;
            }
          }
        }
        .right {
          min-width: 84px;
          height: 56px;
          border-radius: 720px;
          background: v-bind("themeColors.fillColorBg1");
          display: flex;
          align-items: center;
          justify-content: center;
          span {
            color: v-bind("themeColors.textColor");
            font-size: 28px;
          }
          &.right-check-mode {
            div {
              width: 84px;
              height: 56px;
              border-radius: 720px;
              display: flex;
              justify-content: center;
              align-items: center;
              &.active {
                background: v-bind("themeColors.fillColorDarken");
                span {
                  color: v-bind("themeColors.textColorLightest");
                }
              }
            }
          }
        }
      }
    }
  }
  .logout {
    position: absolute;
    left: 40px;
    bottom: 80px;
    span {
      font-size: 32px;
      color: v-bind("themeColors.textColoDanger");
      &:first-child {
        margin-right: 16px;
      }
    }
  }
}
</style>
